﻿using Microsoft.Extensions.Options;
using Yz.Base;
using Yz.Base.Config;
using Yz.Base.Constants;
using Yz.Core.Extensions;

namespace Yz.Manage.Middlewares
{
    public class IpWhiteListMiddleware : BaseMiddleware, IMiddleware
    {
        private readonly WebConfig _webConfig;
        public IpWhiteListMiddleware(IOptions<WebConfig> optionWebConfig)
        {
            _webConfig = optionWebConfig.Value;
        }
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            string clientIp = context.Connection.RemoteIpAddress.ToString();
            if (_webConfig.Validate)//接口不做校验，开始校验ip白名单
            {
                if (_webConfig.WhiteIps == null || !_webConfig.WhiteIps.Contains(clientIp))//不在ip白名单中
                {
                    context.Response.ContentType = BaseDefaultConstant.ContentType;
                    await context.Response.WriteAsync(new VmReturn()
                    {
                        Msg = $"您的Ip {clientIp} 不在Ip白名单中，没有权限访问！"
                    }.ToJsonStr());
                    return;
                }
            }
            await next.Invoke(context);
        }
    }
}
